package com.app.studyroom.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.app.studyroom.AdminUserControlActivity;
import com.app.studyroom.R;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrUser.UserItem;
import com.app.studyroom.api.model.ssrUser.UserUpdateRequest;
import com.app.studyroom.mapper.AreaNameToIdMapper;
import com.app.studyroom.model.MyMultiSelectionSpinner;
import com.app.studyroom.utils.FileUtils;
import com.bumptech.glide.Glide;
import com.google.android.material.imageview.ShapeableImageView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserEditDialog {

    public static Button btnUploadAvatar = null;
    public static ShapeableImageView imgAvatar = null;
    public interface OnUserEditListener {
        void onUserEdited(UserItem updatedUser);
    }
    public static void showEditDialog(Context context, UserItem user, OnUserEditListener listener) {


        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_user, null);
        EditText editName = dialogView.findViewById(R.id.editUserName);
        EditText editPhone = dialogView.findViewById(R.id.editUserSjh);
        EditText editZjh = dialogView.findViewById(R.id.editUserZjh);
        EditText editNumber = dialogView.findViewById(R.id.editUserNumber);
        EditText editClassNumber = dialogView.findViewById(R.id.editClassNumber);
        LinearLayout layout_hide_3 = dialogView.findViewById(R.id.layout_hide_3);
        Spinner spinnerRole = dialogView.findViewById(R.id.spinnerUserBs);
        LinearLayout layout_hide_1 = dialogView.findViewById(R.id.layout_hide_1);
        layout_hide_1.setVisibility(View.GONE);
        Spinner spinnerReservationEnable =dialogView.findViewById(R.id.spinnerReservationEnable);
        LinearLayout layout_hide_2 = dialogView.findViewById(R.id.layout_hide_2);
        MyMultiSelectionSpinner spinnerQyMulti = dialogView.findViewById(R.id.spinnerQyMulti);
        LinearLayout layout_hide = dialogView.findViewById(R.id.layout_hide);


        btnUploadAvatar = dialogView.findViewById(R.id.btnUploadAvatar);
        //预览头像
        imgAvatar = dialogView.findViewById(R.id.img_avatar);
        //默认显示当前头像
        loadCurrentUserAvatar(context, user.getUserImage());

        editName.setText(user.getUserName());
        editPhone.setText(user.getUserSjh());
        editZjh.setText(user.getUserZjh());
        editNumber.setText(user.getUserNumber());
        editClassNumber.setText(user.getClassNum());

        ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{"用户", "区域管理员"});
        roleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerRole.setAdapter(roleAdapter);
        spinnerRole.setSelection(getIndex(spinnerRole, user.getUserBs()));

        // 初始化“是否允许预约”Spinner
        ArrayAdapter<String> enableAdapter = new ArrayAdapter<>(context,
                android.R.layout.simple_spinner_item,
                new String[]{"允许", "禁止"});
        enableAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerReservationEnable.setAdapter(enableAdapter);
        spinnerReservationEnable.setSelection("yes".equals(user.getIsBooking()) ? 0 : 1);


        String[] areaNames = AreaNameToIdMapper.getAllAreaNames();
        spinnerQyMulti.setItems(java.util.Arrays.asList(areaNames));

        // 判断角色是否是“区域管理员”
        if ("区域管理员".equals(user.getUserBs())) {
            //管理员不显示是否允许预约
            layout_hide_2.setVisibility(View.GONE);
            //管理员不显示班级号
            layout_hide_3.setVisibility(View.GONE);
            // 多选区域名称直接作为选中值（无需映射）
            String qyRaw = user.getQy();
            Log.d("回显调试", "原始 QY 字符串（区域名称）: " + qyRaw);
            // 处理分隔符（支持英文逗号和中文逗号），并去除前后空格
            String[] areaNameArray = user.getQy() != null ? user.getQy().split("[,，]") : new String[0];
            java.util.List<String> selectedNames = new java.util.ArrayList<>();
            for (String name : areaNameArray) {
                String trimmed = name.trim(); // 移除空格
                if (!trimmed.isEmpty()) {
                    selectedNames.add(trimmed);
                }
            }
            Log.d("回显调试", "最终选中的区域名称列表: " + selectedNames);

            // 设置多选回显
            spinnerQyMulti.setSelection(selectedNames);


        } else {
            // 非区域管理员禁用
            spinnerQyMulti.setEnabled(false);
            layout_hide.setVisibility(View.GONE);
            spinnerQyMulti.setAlpha(0.5f);
            spinnerQyMulti.clearSelectionOnly();
        }

        AlertDialog dialog = new AlertDialog.Builder(context, R.style.TransparentDialog)
                .setView(dialogView)
                .setCancelable(false)
                .create();

        Button btnMarkGraduate = dialogView.findViewById(R.id.btnMarkGraduate);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);
        Button btnSave = dialogView.findViewById(R.id.btnSave);

        btnMarkGraduate.setOnClickListener(v -> {
            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            UserUpdateRequest graduateRequest = new UserUpdateRequest(user.getId(), "no", "1");

            SharedPreferences sp = context.getSharedPreferences("Session", Context.MODE_PRIVATE);
            String token = sp.getString("token", null);

            if (token == null) {
                Toast.makeText(context, "未登录", Toast.LENGTH_SHORT).show();
                return;
            }

            apiService.userUpdate(token, graduateRequest).enqueue(new Callback<ApiResponse<Object>>() {
                @Override
                public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                        Toast.makeText(context, "标记为毕业成功", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();

                        if (context instanceof AdminUserControlActivity) {
                            ((AdminUserControlActivity) context).isEditDialogShowing = false;
                            ((AdminUserControlActivity) context).loadUserList();
                        }
                    } else {
                        Toast.makeText(context, "操作失败：" + (response.body() != null ? response.body().getMessage() : "未知错误"), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                    Toast.makeText(context, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        btnSave.setOnClickListener(v -> {

            user.setUserName(editName.getText().toString().trim());
            user.setUserSjh(editPhone.getText().toString().trim());
            user.setUserZjh(editZjh.getText().toString().trim());
            user.setUserNumber(editNumber.getText().toString().trim());
            user.setClassNum(editClassNumber.getText().toString().trim());
            user.setUserBs(spinnerRole.getSelectedItem().toString());
            // 设置是否允许预约字段
            String selectedBooking = spinnerReservationEnable.getSelectedItem().toString();
            user.setIsBooking("允许".equals(selectedBooking) ? "yes" : "no");

            if ("区域管理员".equals(user.getUserBs())) {
                // 多选拼接
                java.util.List<String> selectedNames = new java.util.ArrayList<>();
                for (Object obj : spinnerQyMulti.getSelectedItems()) {
                    selectedNames.add(obj.toString());
                }
                java.util.List<String> areaIdList = new java.util.ArrayList<>();
                for (String name : selectedNames) {
                    String id = AreaNameToIdMapper.getIdByName(name);
                    if (id != null) areaIdList.add(id);
                }
                user.setQy(String.join(",", areaIdList));
            } else {
                user.setQy(""); // 非区域管理员无区域或清空
            }
            Runnable callback = () -> {
                Log.d("DialogTrace", "执行回调 onUserEdited");
                if (listener != null) {
                    listener.onUserEdited(user);
                }
                // ✅ 清空已选头像，防止误用
                selectedAvatarUri = null;

                // ✅ 主动关闭对话框
                dialog.dismiss();

                // ✅ 标志清除，允许再次弹出（适用于含 isEditDialogShowing 逻辑的外部场景）
                if (context instanceof AdminUserControlActivity) {
                    ((AdminUserControlActivity) context).isEditDialogShowing = false;
                }
            };
            if (selectedAvatarUri != null) {
                Log.d("DialogTrace", "头像已选择，开始上传...");
                uploadImage(context, user, callback);
            } else {
                Log.d("DialogTrace", "未选择头像，直接执行回调...");
                callback.run();
            }
        });
        btnUploadAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            ((Activity) context).startActivityForResult(Intent.createChooser(intent, "选择头像"), 1003);
        });


        dialog.show();
        // 设置固定宽度为 750dp，高度包裹内容
        int widthInDp = 750;
        float scale = context.getResources().getDisplayMetrics().density;
        int widthInPx = (int) (widthInDp * scale + 0.5f);

        dialog.getWindow().setLayout(widthInPx, LinearLayout.LayoutParams.WRAP_CONTENT);

    }

    private static int getIndex(Spinner spinner, String value) {
        for (int i = 0; i < spinner.getCount(); i++) {
            if (spinner.getItemAtPosition(i).toString().equals(value)) {
                return i;
            }
        }
        return 0;
    }
    public static Uri selectedAvatarUri = null;
    private static void uploadImage(Context context, UserItem user, Runnable onComplete) {
        File file = FileUtils.getFileFromUri(context, selectedAvatarUri);
        if (file == null) {
            Log.e("DialogTrace", "❗FileUtils.getFileFromUri 返回 null，上传终止");
            Toast.makeText(context, "文件无效，无法上传", Toast.LENGTH_SHORT).show();
            onComplete.run();
            return;
        }

        Log.d("DialogTrace", "✔ 文件路径: " + file.getAbsolutePath());

        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.uploadImage(body).enqueue(new Callback<ApiResponse<Map<String, String>>>() {
            @Override
            public void onResponse(Call<ApiResponse<Map<String, String>>> call, Response<ApiResponse<Map<String, String>>> response) {
                Log.d("DialogTrace", "✔ 上传接口响应: " + response.code());
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                    String imageId = response.body().getData().get("id");
                    Log.d("DialogTrace", "✔ 上传成功，imageId = " + imageId);
                    user.setUserImage(imageId);
                } else {
                    Log.e("DialogTrace", "❌ 上传失败: " + response.message());
                }
                onComplete.run();
            }

            @Override
            public void onFailure(Call<ApiResponse<Map<String, String>>> call, Throwable t) {
                Log.e("DialogTrace", "❌ Retrofit onFailure: " + t.getMessage());
                Toast.makeText(context, "上传失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                onComplete.run();
            }
        });
    }
    private static void loadCurrentUserAvatar(Context context, String imageId) {
        if (imageId == null || imageId.isEmpty()) {
            imgAvatar.setImageResource(R.drawable.bg_circle_avatar);
            return;
        }

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Map<String, String> body = new HashMap<>();
        body.put("id", imageId);

        apiService.getImageDetail(body).enqueue(new Callback<ApiResponse<String>>() {
            @Override
            public void onResponse(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getData() != null) {
                    String url = response.body().getData();
                    Glide.with(context)
                            .load(url)
                            .placeholder(R.drawable.bg_circle_avatar)
                            .into(imgAvatar);
                } else {
                    imgAvatar.setImageResource(R.drawable.bg_circle_avatar);
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                imgAvatar.setImageResource(R.drawable.bg_circle_avatar);
            }
        });
    }


}